package tgc.edu.yzy.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tgc.edu.yzy.custom.CommonService;
import tgc.edu.yzy.custom.TreeDTO;
import tgc.edu.yzy.entity.Dapa;
import tgc.edu.yzy.entity.User;
import tgc.edu.yzy.repository.DapaRepositiry;
import tgc.edu.yzy.repository.UserRepository;
@Service
public class DapaService extends CommonService<Dapa, Integer>{
	@Autowired
	private DapaRepositiry dapaDAO;
	@Autowired
	private UserRepository userDAO;
	public List<TreeDTO> tree(Integer id) {
		List<Dapa> tree=dapaDAO.findByParentId(id);
		List<TreeDTO> treeDTO=new ArrayList<>();
		for (Iterator<Dapa> iterator = tree.iterator(); iterator.hasNext();) {
			Dapa trees = (Dapa) iterator.next();
			TreeDTO treed=new TreeDTO();
			treed.setId(trees.getId());
			treed.setText(trees.getName());
			treed.setChecked(trees.getChecked());
			treed.setIconCls(trees.getIcon());
			if(trees.getParent()==null) {
				treed.setParent(null);
			}else {
				treed.setParent(trees.getParent().getId());
			}
			//查询 节点是子节点还是父节点
			List<Dapa> t=dapaDAO.findByParentId(trees.getId());
			if(t.size()>0) {
				treed.setState("closed");
			}else {
				treed.setState("open");
			}
			treeDTO.add(treed);
		}
		return treeDTO;
	}

	public List<Dapa> findByParentId(Integer id) {
		return dapaDAO.findByParentId(id);
	}

	public String findByUser(Integer id,String names) {
		List<Dapa> tree=dapaDAO.findByParentId(id);
		for (int i = 0; i < tree.size(); i++) {
			Integer cid= tree.get(i).getId();
			Dapa dapas = find(cid);
			List<User> user = userDAO.findByDapa(dapas);
			if(user.size()>0) {
				names=names+"有人";
			}
			
			findByUser(cid,names);
		}
		return names;
	}

	private Dapa find(Integer cid) {
		Optional<Dapa> optional = dapaDAO.findById(cid);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}

	
	
	
}
